package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.BehaviorConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.dtos.UserRelationDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserFan;
import com.heima.model.user.pojos.ApUserFollow;
import com.heima.user.mapper.ApUserFanMapper;
import com.heima.user.mapper.ApUserFollowMapper;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import com.heima.utils.common.AppJwtUtil;
import com.heima.utils.thread.AppThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@Slf4j
@Service
@Transactional
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {
    @Autowired
    private ApUserMapper apUserMapper;

    @Autowired
    private CacheService cacheService;
    @Autowired
    private ApUserFanMapper apUserFanMapper;

    @Autowired
    private ApUserFollowMapper apUserFollowMapper;

    @Override
    public ResponseResult login(LoginDto dto) {

        //1.正常登录（手机号+密码登录）
        if (StringUtils.isNoneBlank(dto.getPhone()) && StringUtils.isNoneBlank(dto.getPassword())) {
            //1.1查询用户


//            ApUser apUser1 = apUserMapper.selectOne(lambdaQuery().eq(ApUser::getPhone, dto.getPhone()));

            ApUser apUser = getOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, dto.getPhone()));
            if (apUser == null) {
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "用户不存在");
            }


            //1.2 比对密码
            String salt = apUser.getSalt();
            String pswd = dto.getPassword();
            pswd = DigestUtils.md5DigestAsHex((pswd + salt).getBytes());
            if (!pswd.equals(apUser.getPassword())) {
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
            //1.3 返回数据  jwt
            Map<String, Object> map = new HashMap<>();
            map.put("token", AppJwtUtil.getToken(apUser.getId().longValue()));
            apUser.setSalt("");
            apUser.setPassword("");
            map.put("user", apUser);
            return ResponseResult.okResult(map);
        } else {
            //2.游客  同样返回token  id = 0
            Map<String, Object> map = new HashMap<>();
            map.put("token", AppJwtUtil.getToken(0l));
            return ResponseResult.okResult(map);
        }
    }

    /**
     * 用户关注或取消关注
     *
     * @param dto
     * @return
     */
    @Transactional
    @Override
    public ResponseResult userFollow(UserRelationDto dto) {
        //校验参数
        if (dto==null||dto.getAuthorId()==null||dto.getArticleId()==null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //获取当前用户id
        Integer userID = AppThreadLocalUtil.getUserID();
        if(userID ==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //判断用户是否已经关注
        Integer count = apUserFollowMapper.selectCount(Wrappers.<ApUserFollow>lambdaQuery()
                .eq(ApUserFollow::getUserId, userID)
                .eq(ApUserFollow::getFollowId, dto.getAuthorId()));
        if(count>0){
            //用户已关注取消关注
            //删除用户关注信息
            apUserFollowMapper.delete(Wrappers.<ApUserFollow>lambdaQuery()
                            .eq(ApUserFollow::getUserId, userID)
                            .eq(ApUserFollow::getFollowId, dto.getAuthorId()));

            //删除作者粉丝信息
            apUserFanMapper.delete(Wrappers.<ApUserFan>lambdaQuery()
                    .eq(ApUserFan::getUserId, dto.getAuthorId())
                    .eq(ApUserFan::getFansId, userID));
            //删除用户行为
            cacheService.delete(userID+dto.getArticleId()+BehaviorConstants.APUSER_FOLLOW_RELATION);
        }else {
            //用户未关注添加关注
            //1.获取作者信息和用户信息
            ApUser follow = apUserMapper.selectOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getId, dto.getAuthorId()));
            ApUser apUser = apUserMapper.selectOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getId, userID));

            //为用户添加关注者信息
            ApUserFollow apUserFollow = ApUserFollow.builder()
                    .userId(userID)
                    .followId(dto.getAuthorId())
                    .followName(follow.getName())
                    .createdTime(new Date())
//                    .isNotice(false)
                    .build();
            System.out.println(apUserFollow);
            apUserFollowMapper.insert(apUserFollow);
            //为作者添加粉丝信息
            ApUserFan apUserFan = ApUserFan.builder()
                    .userId(dto.getAuthorId())
                    .fansId(userID)
                    .fansName(apUser.getName())
                    .createdTime(new Date())
//                    .isShieldComment(false)
//                    .isShieldLetter(false)
                    .build();
            apUserFanMapper.insert(apUserFan);
            //添加用户行为
            cacheService.set(userID+dto.getArticleId()+BehaviorConstants.APUSER_FOLLOW_RELATION,userID.toString());
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}